/*
 * Copyright (c) 2013-2020, tanghailan (tanghailan@88.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.kanavi.redisson.business.service;

import cn.hutool.core.util.IdUtil;
import com.kanavi.redisson.business.entity.BatchOrder;
import com.kanavi.redisson.business.entity.BatchOrderParam;
import com.kanavi.redisson.business.entity.Request;
import com.kanavi.redisson.business.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * <b>OrderService.java</b></br>
 *
 * <pre></pre>
 *
 * @author tanghailan tanghailan@88.com
 * @date 2021年03月27日 23:49:09
 * @since JDK 1.8
 */
@Slf4j
@Service
public class JamesOrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RemoteServiceCall remoteServiceCall;

    LinkedBlockingDeque<Request> queue = new LinkedBlockingDeque<>();

    @PostConstruct
    public void init() {
        ScheduledExecutorService scheduled = new ScheduledThreadPoolExecutor(1);
        scheduled.scheduleAtFixedRate(() -> {
            //要做的事情
            int size = queue.size();
            if (size == 0) {
                return;
            }
            //here？  queue一定有数据
            List<Request> requestList = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                Request request = queue.poll();
                requestList.add(request);
            }
            System.out.println("批量处理的数据量为:" + size);
            //拼接批量查询参数格式
            List<BatchOrderParam> params = new ArrayList<>();
            for (Request request : requestList) {
                BatchOrderParam param = new BatchOrderParam();
                param.setOrderCode(request.getOrderCode());
                param.setSerialNo(request.getSerialNo());
                params.add(param);
            }
            List<BatchOrder> responses = remoteServiceCall.queryOrderInfoByCodeBatch(params);
            Map<String, BatchOrder> responseMap = new HashMap<>(1);
            for (BatchOrder response : responses) {
                String serialNo = response.getSerialNo();
                //serialNo -----结果集 一对一
                responseMap.put(serialNo, response);
            }
            for (Request request : requestList) {
                BatchOrder result = responseMap.get(request.getSerialNo());
                request.getFuture().complete(result);
            }
        }, 0, 10, TimeUnit.MILLISECONDS);
    }

    /**
     * <b>queryOrderInfo</b> <br/>
     * <br/>
     * 1000个线程来调用 queryOrderInfo
     * <br/>
     *
     * @param orderCode
     * @return com.kanavi.redisson.business.entity.BatchOrder
     * @author tanghailan tanghailan@88.com
     */

    public BatchOrder queryOrderInfo(String orderCode) throws ExecutionException, InterruptedException {
        //相当于纹身，能代表线程
        String serialNo = IdUtil.randomUUID();
        Request request = new Request();
        request.setSerialNo(serialNo);
        request.setOrderCode(orderCode);
        CompletableFuture<BatchOrder> future = new CompletableFuture<>();
        request.setFuture(future);
        queue.add(request);
        //调用远程接口
        return future.get();
    }
//    return orderService.queryOrderInfoByCode(orderCode);
}
